package com.tangguangdi.shield.server.receiver;


import com.alibaba.fastjson.JSON;
import com.tangguangdi.shield.server.permission.PermissionCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

@Slf4j
public class MessageReceiver implements MessageListener {

    @Autowired
    private ApplicationEventPublisher publisher;
    @Autowired
    private PermissionCache cache;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String topic = new String(message.getChannel());
        String msg = new String(message.getBody());
        log.info(String.format("message receive successful. topic: %s msg: %s."
                , topic, msg));
        cache.update(JSON.parse(msg).toString());
        this.publisher.publishEvent(new RefreshRoutesEvent(this));
    }
}
